﻿using BugAdmin.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;

namespace BugAdmin.Api.Controllers
{
    /// <summary>
    /// 数据库初始化操作控制器
    /// </summary>
    [Route("[controller]/[Action]")]
    [ApiController]
    public class DBController : ControllerBase
    {
        private ILogger<DBController> _logger;
        private ISqlSugarClient _db;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="db"></param>
        public DBController(ILogger<DBController> logger,ISqlSugarClient db)
        {
            _logger = logger;
            _db = db;   
        }
        /// <summary>
        /// 初始化并创建数据库
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> InitDB()
        {
            //创建数据库
            bool bRet= _db.DbMaintenance.CreateDatabase();
            if (!bRet)
            {
                _logger.LogInformation("创建数据库失败");
                return false;
            }
            _logger.LogInformation("创建数据库成功");
            //通过反射加载程序集,，查找需要加载的命名空间下的实体
            Type[] ass = Assembly.LoadFrom(AppContext.BaseDirectory + "BugAdmin.Model.dll").GetTypes().Where(p => p.Namespace == "BugAdmin.Model.Entity").ToArray();
            //根据创建创建表（设置字段默认长度为200）
            _db.CodeFirst.SetStringDefaultLength(200).InitTables(ass);
            _logger.LogInformation("创建数据表成功");

            return true;
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> InitData()
        {
            User user = new User()
            {
                Name="Admin",
                Password="123456",
                UserType=1,
                Phone="18888888888",
                Mobile="0291234567",
                Email="admin@163.com",
                Address="西安市",
                QQ="001",
                WeChat="W001",
                Sex=1,
                ImageUrl=""
            };
            int falg=await _db.Insertable<User>(user).ExecuteCommandAsync();
            return falg>0?true:false;
        }


    }
}
